require('./utils/handleUncaughtException');
const Koa = require('koa');
const send = require('koa-send');
const Router = require('koa-router');
const config = require('./config');
const log = require('./log');
const log4js = require('./utils/log4js');

const severEndLogger = log4js.severEndLogger;
const logRuntimeError = log.runtimeError;
const logLoadScriptError = log.loadScriptError;

const app = new Koa();
const router = new Router();

/**
 *	全局捕获
 * @param {*} context
 * @param {*} next
 */
async function throwError(context, next) {
	try {
		await next();
	} catch (error) {
		severEndLogger.error(error.message);
		context.status = error.statusCode || error.status || 500;
		context.body = {
			message: error.message,
		};
		// await sendStaticResource(context, '/1pixel.png');
	}
}

async function sendStaticResource(context, path) {
	await send(context, path, { root: config.publicDir });
}

/**
 * 过滤不能解析文件 判断 xxx.js.map文件
 * @param {*} context 
 * @param {*} next 
 */
function excludeHtmlError(context, next){
	const fileurl =  context.request.query && context.request.query.fileurl ?context.request.query.fileurl: '';
	if (/.+\.js\.map$/.test(fileurl)){ // 判断 xxx.js.map文件
		next();
	} else {
		context.throw('不存在source map文件:'+ fileurl);
	}
}

app
	.use(throwError)
	// .use(excludeHtmlError)
	.use(router.routes())
	.use(router.allowedMethods());


router
	.get('/runtime', async (context, next) => {
		const params = Object.assign({},context.request.query, {
			userAgent: context.header['user-agent'],
			referer: context.header['referer'],
			ip: context.ip,
		});
		await logRuntimeError(params);
		await sendStaticResource(context, '/1pixel.png');
	})
	.get('/loadScript', async (context, next) => {
		const params = Object.assign({},context.request.query, {
			userAgent: context.header['user-agent'],
			referer: context.header['referer'],
			ip: context.ip,
		});
		await logLoadScriptError(params);
		await sendStaticResource(context, '/1pixel.png');
	})
	.all('/*', async (context, next) => {
		severEndLogger.error(
			`Not Found - [href: ${context.href}]	[ip: ${context.ip}]	[user-agent: ${context.header['user-agent']}]`
		);
		// await sendStaticResource(context, '/1pixel.png');
		context.response.status = 404;
		context.response.body = '<h1>404 Not Found</h1>';
	});

app.listen(3000);
